<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.code"
          size="small"
          clearable
          placeholder="编码"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.name"
          size="small"
          clearable
          placeholder="名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.dsSource"
          size="small"
          clearable
          placeholder="源数据源"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.sourceTable"
          size="small"
          clearable
          placeholder="源表名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.dsTarget"
          size="small"
          clearable
          placeholder="目标数据源"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.targetTable"
          size="small"
          clearable
          placeholder="目标表名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.projectName"
          size="small"
          style="width: 200px;"
          class="filter-item"
          clearable
          placeholder="所属公司"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in dict.project_name"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :router-name="query.routerName" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <customBtns :permission="permission" :route-path="routePath" />
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        stripe
        border
        style="width: 100%;"
        @row-dblclick="editFiled"
        @sort-change="sortChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column prop="code" label="编码" sortable="custom" />
        <el-table-column
          prop="name"
          label="名称"
          sortable="custom"
          width="130"
        />
        <el-table-column
          prop="dsSource"
          label="源数据源"
          sortable="custom"
          width="130"
        />
        <el-table-column prop="sourceTable" label="源表名" sortable="custom" />
        <el-table-column
          prop="dsTarget"
          label="目标数据源"
          sortable="custom"
          width="130"
        />
        <el-table-column
          prop="targetTable"
          label="目标表名"
          sortable="custom"
        />
        <el-table-column
          prop="projectName"
          label="所属公司"
          sortable="custom"
        />
        <el-table-column
          prop="execState"
          width="60"
          label="执行中"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.execState == 1">
              <img class="exec-loading" src="../../assets/images/loading.gif">
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column v-permission="['admin','migDefMain:edit','migDefMain:del']" -->
        <el-table-column
          v-permission="['migDefMain:edit']"
          label="操作"
          width="140px"
          align="center"
        >
          <template slot-scope="scope">
            <customOperation
              :data="scope.row"
              :permission="permissionRow"
              @configFiled="configFiled"
              @editFiled="editFiled"
            />

            <el-tooltip
              class="item"
              :hide-after="crud.CONSTOM.TIP_TIME"
              effect="dark"
              content="执行迁移任务"
              placement="top-start"
            >
              <el-button
                size="mini"
                type="success"
                icon="el-icon-caret-right"
                @click="execMigTask(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
/* eslint-disable */

import crudMigDefMain from "@/api/migrate/migDefMain";
import {
  getOrginSource,
  getTables,
  doMigrate
} from "@/api/migrate/coustomFunction";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import crudOperation from "@crud/CRUD.operation";
import customBtns from "@crud/customBtns";
import rrOperation from "@crud/RR.operation";
import customOperation from "@crud/customOperation";
import pagination from "@crud/Pagination";
// import DateRangePicker from "@/components/DateRangePicker";

import qs from "qs";
const defaultForm = {
  id: null,
  code: null,
  name: null,
  sourceTable: null,
  targetTable: null,
  dsSource: null,
  dsTarget: null,
  extClass: null,
  sourcePk: null,
  targetPk: null,
  extJson: null,
  fdIncr: null,
  incrValue: null,
  querySql: null,
  lastSyncTime: null,
  syncTableDdl: null,
  fdTitle: null,
  fdEmergency: null,
  fdCode: null,
  recordLog: null,
  delFlag: null,
  createTime: null,
  updateTime: null,
  memo: null
};
export default {
  name: "MigDefMain",
  components: {
    pagination,
    crudOperation,
    customOperation,
    rrOperation,
    // DateRangePicker,
    customBtns
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    const formData = CRUD({
      query: {
        code: "",
        name: "",
        dsSource: "",
        sourceTable: "",
        dsTarget: "",
        targetTable: ""
      },
      //只有在doNotQuery为true的情况下才不走页面初始化时系统的第一次查询
      doNotQuery: true,
      title: "迁移数据定义",
      url: "api/migDefMain",
      sort: "id,desc",
      crudMethod: { ...crudMigDefMain }
    });
    return formData;
  },
  // 设置数据字典
  dicts: ["project_name"],
  watch: {
    form: {
      deep: true,
      handler(val) {
        val.syncTableDdl = val.syncTableDdl ? ~~val.syncTableDdl : 2;
        val.recordLog = val.recordLog ? val.recordLog : 2;
        val.delFlag = val.delFlag ? val.delFlag : 2;
      }
    }
  },
  data() {
    return {
      timer: new Date().getTime(),
      targetDialog: false,
      width: 270,
      sourceDsSourceArr: [], //数据源的列表
      sourceTableArr: [], //源数据源对应表
      targetTableArr: [], //目标数据源对应表
      dialogArr: [],
      originArr: [],
      configData: [],
      checkSourceTableShow: false, //是否显示选择原始表的弹框
      checkTargetTableShow: false, //是否显示显示目标表的弹框
      configDialog: false,
      permission: {
        add: ["admin", "migDefMain:add"],
        edit: ["admin", "migDefMain:edit"],
        del: ["admin", "migDefMain:del"],
        config: true
      },
      routePath: {
        add: "/migDefAdd",
        edit: "/migDefEdit",
        PK_FIELD: "id"
      },
      permissionRow: {
        edit: ["admin", "migDefMain:edit"],
        del: ["migDefMain:del"],
        config: true
      },
      rules: {
        code: [{ required: true, message: "编码不能为空", trigger: "blur" }],
        dsSource: [
          { required: true, message: "源数据源不能为空", trigger: "blur" }
        ],
        sourceTable: [
          { required: true, message: "源表名不能为空", trigger: "blur" }
        ],
        dsTarget: [
          { required: true, message: "目标数据源不能为空", trigger: "blur" }
        ],
        targetTable: [
          { required: true, message: "目标表名不能为空", trigger: "blur" }
        ],
        sourcePk: [
          { required: true, message: "源表主键不能为空", trigger: "blur" }
        ],
        targetPk: [
          { required: true, message: "目标表名主键不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.query.routerName = this.$route.name || "";
    let sessionQueryData = "";
    try {
      sessionQueryData = JSON.parse(
        sessionStorage.getItem(this.query.routerName)
      );
    } catch (e) {
      console.error(e.message);
    }
    if (sessionQueryData) {
      Object.assign(this.query, sessionQueryData);
    }
    // 查询的标识 true查询
    this.query.relation = true;
    this.crud.refresh();
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      //是否判断 true 判断
      this.query.unQuery = true;
      return true;
    },
    sortChange(data = {}) {
      const prop = data.prop;
      const order =
        data.order == "ascending" || data.order == "asc" ? "asc" : "desc";
      if (prop) {
        this.crud.sort = [`${prop},${order}`];
        this.crud.toQuery();
      }
    },
    getOrgin() {
      //数据源的列表
      getOrginSource().then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.name,
              value: i.name
            });
          });
          this.sourceDsSourceArr = arr;
        }
      });
    },
    getDsSourceTables(val, changeFlag) {
      //获取源数据源的表
      this.sourceTableArr = [];
      if (changeFlag != false) {
        this.form.sourceTable = "";
      }
      let params = {
        dsName: val
      };
      getTables(params).then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.description,
              value: i.name
            });
          });
          this.sourceTableArr = arr;
        }
      });
    },
    getDsTargetTables(val, changeFlag) {
      //获取目标数据源的表
      this.targetTableArr = [];
      if (changeFlag != false) {
        //changeFlag为false的时候，不改变页面上的值
        this.form.targetTable = "";
      }

      let params = {
        dsName: val
      };
      getTables(params).then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.description,
              value: i.name
            });
          });
          this.targetTableArr = arr;
        }
      });
    },

    selectSourceTable(index, label, value) {
      //选择原始表
      this.form.sourceTable = value;
      this.checkSourceTableShow = false;
    },

    selectTargetTable(index, label, value) {
      // 选择目标表
      this.form.targetTable = value;
      this.checkTargetTableShow = false;
    },

    openSelectSourceTable() {
      //打开选择原表
      if (this.sourceTableArr.length == 0) {
        this.getDsSourceTables(this.form.dsSource, false);
      }
      this.checkSourceTableShow = true;
    },

    openSelectTargetTable() {
      if (this.targetTableArr.length == 0) {
        this.getDsTargetTables(this.form.dsTarget, false);
      }
      this.checkTargetTableShow = true;
    },

    configFiled(data) {
      const query = {
        id: data.id,
        dsName: data.dsTarget,
        tableName: data.targetTable,
        fieldName: data.dsSource,
        table: data.sourceTable,
        PK_FIELD: "id"
      };
      this.$router.push({
        path: "/migDefItem",
        query
      });
    },
    editFiled(data) {
      let query = data;
      query.queryEdit = true;
      query.PK_FIELD = "code";
      this.$router.push({
        name: "MigDefEdit",
        query
      });
    },
    execMigTask(data) {
      var that = this;
      var messageStr = "是否确定执行迁移 " + data.name;
      this.$confirm(messageStr, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var params = { migCode: data.code }; // 这里执行的时候传CODE
          this.$message("已开始执行");
          doMigrate(params).then(res => {
            that.crud.refresh();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped>
.filedWidth {
  width: 350px;
}
.checkFiledWidth {
  width: 330px;
}
.filedWidthLong {
  width: 800px;
}
</style>
<style>
.formClass .el-form-item label.el-form-item__label {
  font-weight: normal;
}
.formClass {
  display: flex;
  flex-wrap: wrap;
}
.dialog-footer {
  text-align: center;
}
.dialog-footer button {
  margin: auto 50px;
}
.searchFiled {
  padding-right: 20px;
  position: relative;
}
.searchIcon {
  position: absolute;
  right: 5px;
  top: 6px;
  cursor: pointer;
  font-size: 16px;
  color: #42b983;
  margin-left: 4px;
}

.check_ul {
  display: flex;
  flex-wrap: wrap;
}
.check_li {
  display: inline-block;
  line-height: 30px;
  height: 30px;
  text-align: center;
  border: 1px solid #eee;
  margin: 0 10px 10px 0;
  padding: 0 8px;
  cursor: pointer;
}
.li_checked {
  background-color: #eee;
}

.exec-loading {
  width: 29px;
  height: 29px;
}
</style>
